//
//  PicViewController.m
//  miaopai
//
//  Created by Crow Zhang on 15/11/12.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "PicViewController.h"
#import "MacroDefinition.h"
#import "DEFINE.h"
#import "LastPicCollectionViewCell.h"
#import "CoreData.h"
#import "CustomerNetworking.h"
#import <MJRefresh.h>
#import "SomePicture.h"
#import "UMSocial.h"
@interface PicViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>

@property (nonatomic, retain) UISegmentedControl *segment;

@property (nonatomic, retain) CoreData *coreDataManager;

/*********************************第一张视图********************/
@property (nonatomic, retain) UIView *lastView; // 第一张视图

@property (nonatomic, retain) NSMutableArray *lastArr; // 第一张数据

@property (nonatomic, retain) UICollectionView *lastCollectionView; // 第一张 collectionView

@property (nonatomic, retain) MJRefreshNormalHeader *lastHeader; // 下拉

@property (nonatomic, retain) MJRefreshAutoNormalFooter *lastFooter; // 上拉

/***********************************第二章视图*******************************/
@property (nonatomic, retain) UIView *someView; // 第二张 视图

@property (nonatomic, retain) NSMutableArray *someArr; // 第二张数据

@property (nonatomic, retain) UICollectionView *someCollectionView; // 第二张 collectionView

@property (nonatomic, retain) MJRefreshNormalHeader *someHeader; // 下拉

@property (nonatomic, retain) MJRefreshAutoNormalFooter *someFooter; // 上啦

@end

@implementation PicViewController


-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.lastArr = [NSMutableArray array];
        self.someArr = [NSMutableArray array];

//        第一张视图
        self.lastHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadLastData)];
        self.lastFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadLastMoreData)];
//        第二张视图
        self.someHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadSomeData)];
        self.someFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadSomeMoreData)];
//        coreData
        self.coreDataManager = [CoreData shareManagerWithFile:@"joke"];


//        网络解析
        [self loadLastData];
        [self loadSomeData];
    }
    return self;
}

//    加载更多
static int i = 2;
static int j = 2;
- (void)loadLastMoreData{
    [CustomerNetworking customerConnectWithURL:[NSString stringWithFormat:@"http://joke.luckyamy.com/api/?cat=pic&p=%d&ap=ymds&ver=1.6", i++] andparameters:nil andBlock:^(id response) {

        for (NSDictionary *dic in response) {
            LastPicture *pic = [NSEntityDescription insertNewObjectForEntityForName:@"LastPicture" inManagedObjectContext:_coreDataManager.managedObjectContext];
            pic.text = [dic objectForKey:@"text"];
            pic.created_at = [dic objectForKey:@"created_at"];
            pic.playurl = [dic objectForKey:@"playurl"];
            pic.original = [dic objectForKey:@"original"];
            pic.width = [dic objectForKey:@"width"];
            pic.height = [dic objectForKey:@"height"];
            [self.lastArr addObject:pic];
        }

        [self.lastFooter endRefreshing];
        [_lastCollectionView reloadData];
    }];
}

- (void)loadSomeMoreData{
    [CustomerNetworking customerConnectWithURL:[NSString stringWithFormat:@"http://joke.luckyamy.com/api/?cat=pic&type=random&p=%d&time=1405767095&ap=ymds&ver=1.6", j++] andparameters:nil andBlock:^(id response) {

        for (NSDictionary *dic in response) {
            SomePicture *pic = [NSEntityDescription insertNewObjectForEntityForName:@"SomePicture" inManagedObjectContext:_coreDataManager.managedObjectContext];
            pic.text = [dic objectForKey:@"text"];
            pic.created_at = [dic objectForKey:@"created_at"];
            pic.playurl = [dic objectForKey:@"playurl"];
            pic.original = [dic objectForKey:@"original"];
            pic.width = [dic objectForKey:@"width"];
            pic.height = [dic objectForKey:@"height"];
            [self.someArr addObject:pic];
        }

        [self.someFooter endRefreshing];
        [_someCollectionView reloadData];
    }];
}

#pragma mark - 给字典赋值
- (void)searchLastData{ // 第一张视图的数据

    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"LastPicture"];
    NSArray *array = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    [self.lastArr addObjectsFromArray:array];

}

- (void)searchSomeData{ // 第二张视图的数据

    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"SomePicture"];
    NSArray *array = [_coreDataManager.managedObjectContext executeFetchRequest:request error:nil];
    [self.someArr addObjectsFromArray:array];
}


- (void)viewWillAppear:(BOOL)animated{
    [self loadLastData];
    [self loadSomeData];
}

#pragma mark - 数据解析
- (void)loadLastData{ // 第一张视图的数据

    //        首先进来先给数组赋值
    [self searchLastData];

    [CustomerNetworking customerConnectWithURL:PIC_FIRST andparameters:nil andBlock:^(id response) {

//        请求数据回来后, 把原来的数据删除
        for (LastPicture *pic in self.lastArr) {
            [_coreDataManager.managedObjectContext deleteObject:pic];
        }
        [self.lastArr removeAllObjects];

        for (NSDictionary *dic in response) {
            LastPicture *pic = [NSEntityDescription insertNewObjectForEntityForName:@"LastPicture" inManagedObjectContext:_coreDataManager.managedObjectContext];
            pic.text = [dic objectForKey:@"text"];
            pic.created_at = [dic objectForKey:@"created_at"];
            pic.playurl = [dic objectForKey:@"playurl"];
            pic.original = [dic objectForKey:@"original"];
            pic.width = [dic objectForKey:@"width"];
            pic.height = [dic objectForKey:@"height"];
            [_coreDataManager saveContext];
        }
        [self searchLastData];
        [self.lastHeader endRefreshing];
        [self.lastCollectionView reloadData];
        i = 2;
    }];
}

- (void)loadSomeData{ // 第二张视图的数据
    //        首先进来先给数组赋值
    [self searchSomeData];

    [CustomerNetworking customerConnectWithURL:PIC_SECOND andparameters:nil andBlock:^(id response) {

        //        请求数据回来后, 把原来的数据删除
        for (SomePicture *pic in self.someArr) {
            [_coreDataManager.managedObjectContext deleteObject:pic];
        }
        [self.someArr removeAllObjects];

        for (NSDictionary *dic in response) {
            SomePicture *pic = [NSEntityDescription insertNewObjectForEntityForName:@"SomePicture" inManagedObjectContext:_coreDataManager.managedObjectContext];
            pic.text = [dic objectForKey:@"text"];
            pic.created_at = [dic objectForKey:@"created_at"];
            pic.playurl = [dic objectForKey:@"playurl"];
            pic.original = [dic objectForKey:@"original"];
            pic.width = [dic objectForKey:@"width"];
            pic.height = [dic objectForKey:@"height"];
            [_coreDataManager saveContext];
        }
        [self searchSomeData];
        [self.someHeader endRefreshing];
        [self.someCollectionView reloadData];
        j = 2;
    }];
}

- (void)dealloc
{
    [_someCollectionView release];
    [_someHeader release];
    [_someFooter release];
    [_someView release];
    [_someArr release];
    [_lastFooter release];
    [_lastHeader release];
    [_segment release];
    [_coreDataManager release];
    [_lastCollectionView release];
    [_lastArr release];
    [_lastView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    self.title = @"搞笑图片";
    self.automaticallyAdjustsScrollViewInsets = NO;
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleDone target:self action:@selector(back:)];
    self.navigationItem.leftBarButtonItem = backItem;

//    创建视图
    [self creatView];
}
//    segment 的点击事件
- (void)segmentAction:(UISegmentedControl *)segment{
        if (segment.selectedSegmentIndex == 0) {
            [self.view insertSubview:_lastView aboveSubview:_someView];
            return;
        }
    [self.view insertSubview:_someView aboveSubview:_lastView];
}

#pragma mark - 创建视图
- (void)creatView{

    self.segment = [[UISegmentedControl alloc] initWithItems:@[@"最新更新", @"随机穿越"]];
    [_segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    self.segment.selectedSegmentIndex = 0;
    self.navigationItem.titleView = self.segment;
    [_segment release];

/*****************************第二张视图*******************/
    self.someView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    self.someView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_someView];
    [_someView release];

    UICollectionViewFlowLayout *someFlowLayout = [[UICollectionViewFlowLayout alloc] init];

//    模块的间距
    someFlowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
//    滑动方向
    someFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;

    self.someCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, _someView.Width, _someView.Height) collectionViewLayout:someFlowLayout];
    _someCollectionView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:0.5];

    _someCollectionView.mj_header = _someHeader;
    _someCollectionView.mj_footer = _someFooter;

    _someCollectionView.mj_header = _someHeader;
    _someCollectionView.mj_footer = _someFooter;

    _someCollectionView.delegate = self;
    _someCollectionView.dataSource = self;
    [_someView addSubview:_someCollectionView];
    [_someCollectionView release];
    [someFlowLayout release];
    [_someCollectionView registerClass:[LastPicCollectionViewCell class] forCellWithReuseIdentifier:@"someCollectionViewCell"];
/*********************************第一张视图**********************/
    self.lastView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 64)];
    self.lastView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.lastView];
    [_lastView release];

    UICollectionViewFlowLayout *lastFlowLayout = [[UICollectionViewFlowLayout alloc] init];
//    模块的间距
    lastFlowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
//    模块的滑动方向
    lastFlowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;

    self.lastCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, _lastView.Width, _lastView.Height) collectionViewLayout:lastFlowLayout];
    _lastCollectionView.backgroundColor =  [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:0.5];

    _lastCollectionView.mj_header = self.lastHeader;
    _lastCollectionView.mj_footer = self.lastFooter;

    _lastCollectionView.mj_header = self.lastHeader;
    _lastCollectionView.mj_footer = self.lastFooter;

    _lastCollectionView.delegate = self;
    _lastCollectionView.dataSource = self;
    [_lastView addSubview:_lastCollectionView];
    [lastFlowLayout release];
    [_lastCollectionView release];
    [_lastCollectionView registerClass:[LastPicCollectionViewCell class] forCellWithReuseIdentifier:@"lastPicCollectionView"];



}


#pragma mark - 协议 
#pragma mark - collectionView 的协议
//    行高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat vHeight = SCREEN_HEIGHT / 20;
    CGFloat imageHeight = SCREEN_HEIGHT / 30;


//    判断一下是那个视图
    if (collectionView == _lastCollectionView) { // 第一个页面
        LastPicture *pic = [self.lastArr objectAtIndex:indexPath.item];
        BOOL Screen_width = [pic.width floatValue] < (SCREEN_WIDTH - 20) ? YES : NO;
        if (Screen_width) {
            CGFloat height = vHeight + 5 + [LastPicCollectionViewCell heightOfText:pic.text] + [pic.height floatValue] + imageHeight + 15;
            return CGSizeMake(SCREEN_WIDTH - 20, height);
        }

        CGFloat width = [pic.width floatValue] / SCREEN_WIDTH;
        //    CGFloat height = [pic.height floatValue] / width;
        CGFloat height = vHeight + 5 + [LastPicCollectionViewCell heightOfText:pic.text] + [pic.height floatValue] / width + imageHeight + 15;
        return CGSizeMake(SCREEN_WIDTH - 20, height);
    }

//    第二个页面
    SomePicture *pic = [self.someArr objectAtIndex:indexPath.item];
    BOOL Screen_width = [pic.width floatValue] < (SCREEN_WIDTH - 20) ? YES : NO;
    if (Screen_width) {
        CGFloat height = vHeight + 5 + [LastPicCollectionViewCell heightOfText:pic.text] + [pic.height floatValue] + imageHeight + 15;
        return CGSizeMake(SCREEN_WIDTH - 20, height);
    }
    CGFloat width = [pic.width floatValue] / SCREEN_WIDTH;
    CGFloat height = vHeight + 5 + [LastPicCollectionViewCell heightOfText:pic.text] + [pic. height floatValue] / width + imageHeight + 15;
    return CGSizeMake(SCREEN_WIDTH - 20, height);
}
//    行数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == _lastCollectionView) {
        return self.lastArr.count;
    }
    return self.someArr.count;
}
//    详细内容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == _lastCollectionView) {
        LastPicCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"lastPicCollectionView" forIndexPath:indexPath];
        cell.lastPic = [self.lastArr objectAtIndex:indexPath.item];
        [cell shareButtonClick:^{
//            [UMSocialSnsService presentSnsController:self appKey:@"565415bfe0f55aaf68000909" shareText:@"" shareImage:@"" shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,nil] delegate:NULL];
            [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeImage url:cell.lastPic.original];
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:@"56554e9967e58e6ff800226b"
                                              shareText:@"发现了一张好图"
                                             shareImage:nil
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,UMShareToTencent,nil]
                                               delegate:nil];
        }];
        
        return cell;
    } else {
        LastPicCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"someCollectionViewCell" forIndexPath:indexPath];
        cell.somePic = [self.someArr objectAtIndex:indexPath.item];
        [cell shareButtonClick:^{
//            [UMSocialSnsService presentSnsController:self appKey:@"565415bfe0f55aaf68000909" shareText:@"" shareImage:@"" shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,nil] delegate:NULL];
            
            [[UMSocialData defaultData].urlResource setResourceType:UMSocialUrlResourceTypeImage url:cell.somePic.original];
            [UMSocialSnsService presentSnsIconSheetView:self
                                                 appKey:@"56554e9967e58e6ff800226b"
                                              shareText:@"发现了一张好图"
                                             shareImage:nil
                                        shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToDouban,UMShareToRenren,UMShareToTencent,nil]
                                               delegate:nil];
        }];
        return cell;
    }


}


#pragma mark -
- (void)back:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}



@end
